package com.tledu.web04.controller;

import com.tledu.web04.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;

@WebServlet(urlPatterns = "/student/edit")
public class StudentEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");

        HashMap<String, Student> studentData = (HashMap<String, Student>) this.getServletContext().getAttribute("studentData");

        Student student = studentData.get(username);
        req.setAttribute("student", student);
        req.getRequestDispatcher("/WEB-INF/view/studentEdit.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
        // 增加一个校验，如果登录继续进行，没有登录，定向到登录界面
        // 判断是否登录
//        HttpSession session = req.getSession();
//        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
//        if (isLogin == null || !isLogin) {
//            // 进行重定向
//            resp.sendRedirect(req.getContextPath() + "/login.jsp");
//            return;
//        }

        // 获取这些数据进行封装
        Student student = new Student();
        student.setUsername(req.getParameter("username"));
        student.setPassword(req.getParameter("password"));
        student.setNickname(req.getParameter("nickname"));
        student.setAge(Integer.parseInt(req.getParameter("age")));
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            student.setBirthday(simpleDateFormat.parse(req.getParameter("birthday")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 把这个对象存起来
        HashMap<String, Student> studentData = (HashMap<String, Student>) this.getServletContext().getAttribute("studentData");
        // 这个key应该不存在的
        studentData.put(student.getUsername(), student);
        resp.sendRedirect(req.getContextPath()+"/student");
    }
}
